<?php

namespace App\Http\Controllers;

use App\Http\Common\JWT;
use App\Models\AdminUser;
use phpDocumentor\Reflection\DocBlock\Description;
use Request;
use Laravel\Lumen\Routing\Controller as BaseController;

class Controller extends BaseController
{

    protected $request;

    public function __construct()
    {
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:OPTIONS,POST,GET,PUT,DELETE');
        header('Access-Control-Allow-Headers:requesttype,x-requested-with,content-type');
    }

    public function makeResponse($data = [], $msg = '', $code = 500)
    {
        return compact('code', 'msg', 'data');
    }

    public function return_json($code, $data, $msg)
    {
        $data = ['code' => $code, 'data' => $data, 'msg' => $msg];
        return response()->json($data);
    }

    public function assoc_unique($arr, $key)
    {
        $tmp_arr = array();
        foreach ($arr as $k => $v) {
            if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
                unset($arr[$k]);
            } else {
                $tmp_arr[] = $v[$key];
            }
        }
        sort($arr); //sort函数对数组进行排序
        return $arr;
    }

    public function searchmax($arr, $field) // 最小值 只需要最后一个max函数  替换为 min函数即可
    {
        if (!is_array($arr) || !$field) { //判断是否是数组以及传过来的字段是否是空
            return false;
        }

        $temp = array();
        foreach ($arr as $key => $val) {
            $temp[] = $val[$field]; // 用一个空数组来承接字段
        }
        return max($temp);  // 用php自带函数 max 来返回该数组的最大值，一维数组可直接用max函数
    }

    public function checkToken($request)
    {
        $request = new \Illuminate\Http\Request();
        $header = $request->header();

        if (!$header) {
            return $this->makeResponse([], '登录失效!', 401);
        };
        $token = substr($header, 7);

        $jwtToken = JWT::verifyToken($token);

        if ($jwtToken['jti'] !== env('JWT_CODE')) {
            return $this->makeResponse([], '签名错误', 500);
        } else {
            $user = AdminUser::where(['username' => $jwtToken['name']])->first()->toArray();
            $status = passwordVerify($jwtToken['pass'], $user['password']);
            unset($user['password']);

            if ($status) {
                return $user;

            } else {
                return $this->makeResponse([], 'Token验证失败~', 500);
            }

        }

    }

    public function getUserInfo($request)
    {
        $data = $this->checkToken($request);
        return $data;
    }
}
